﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DH.MQ
{
    class RedisHelper
    {
        private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"];

        

        #region -- 连接信息 --
        //10.0.18.8:6379
        public static PooledRedisClientManager prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath });


        private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
        {
            // 支持读写分离，均衡负载 
            PooledRedisClientManager pcm = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
            {
                MaxWritePoolSize = 5, // “写”链接池链接数 
                MaxReadPoolSize = 5, // “读”链接池链接数 
                AutoStart = true
            });
            pcm.ConnectTimeout = 1;
            return pcm;
        }


        #endregion

        #region -- Item --
        /// <summary>
        /// 设置单体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <param name="timeSpan"></param>
        /// <returns></returns>
        public static bool Item_Set<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    bool res = redis.Set<T>(key, t, new TimeSpan(1, 0, 0));
                    return res;
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Item_Set", Enum_LogType.Error, ex.Message);
                    return false;
                }
            }


        }

        /// <summary>
        /// 获取单体
        /// </summary>
        /// <typeparam name="T"></typeparam>%
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Item_Get<T>(string key) where T : class
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.Get<T>(key);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Item_Get", Enum_LogType.Error, ex.Message);
                    return null;
                }

            }
        }

        /// <summary>
        /// 移除单体
        /// </summary>
        /// <param name="key"></param>
        public static bool Item_Remove(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.Remove(key);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Item_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }

        /// <summary>
        /// 设置单体缓存过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="datetime"></param>
        public static void Item_SetExpire(string key, DateTime datetime)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    redis.ExpireEntryAt(key, datetime);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Item_SetExpire", Enum_LogType.Error, ex.Message);
                }
            }
        }


        #endregion

        #region -- List --

        public static void List_Add<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_Add", Enum_LogType.Error, ex.Message);
                }
            }
        }



        public static bool List_Remove<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0;
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }
            }
        }
        public static void List_RemoveAll<T>(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    redisTypedClient.Lists[key].RemoveAll();
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_RemoveAll", Enum_LogType.Error, ex.Message);
                }

            }
        }

        public static long List_Count(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.GetListCount(key);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_Count", Enum_LogType.Error, ex.Message);
                    return 0;
                }

            }
        }

        public static List<T> List_GetRange<T>(string key, int start, int count)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var c = redis.As<T>();
                    return c.Lists[key].GetRange(start, start + count - 1);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_GetRange", Enum_LogType.Error, ex.Message);
                    return null;
                }
            }
        }


        public static List<T> List_GetList<T>(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var c = redis.As<T>();
                    return c.Lists[key].GetRange(0, c.Lists[key].Count);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_GetList", Enum_LogType.Error, ex.Message);
                    return null;
                }

            }
        }

        public static List<T> List_GetList<T>(string key, int pageIndex, int pageSize)
        {
            int start = pageSize * (pageIndex - 1);
            return List_GetRange<T>(key, start, pageSize);
        }

        /// <summary>
        /// 设置缓存过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="datetime"></param>
        public static void List_SetExpire(string key, DateTime datetime)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    redis.ExpireEntryAt(key, datetime);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.List_SetExpire", Enum_LogType.Error, ex.Message);
                }

            }
        }
        #endregion

        #region -- Set --
        public static void Set_Add<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    redisTypedClient.Sets[key].Add(t);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Set_Add", Enum_LogType.Error, ex.Message);
                }

            }
        }
        public static bool Set_Contains<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    return redisTypedClient.Sets[key].Contains(t);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Set_Contains", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        public static bool Set_Remove<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var redisTypedClient = redis.As<T>();
                    return redisTypedClient.Sets[key].Remove(t);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Set_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        #endregion

        #region -- Hash --
        /// <summary>
        /// 判断某个数据是否已经被缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public static bool Hash_Exist<T>(string key, string dataKey)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.HashContainsEntry(key, dataKey);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_Exist", Enum_LogType.Error, ex.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 存储数据到hash表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public static bool Hash_Set<T>(string key, string dataKey, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.SetEntryInHash(key, dataKey, value);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_Set", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        /// <summary>
        /// 移除hash中的某值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public static bool Hash_Remove(string key, string dataKey)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.RemoveEntryFromHash(key, dataKey);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        /// <summary>
        /// 移除整个hash
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public static bool Hash_Remove(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.Remove(key);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        /// <summary>
        /// 从hash表获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public static T Hash_Get<T>(string key, string dataKey)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    string value = redis.GetValueFromHash(key, dataKey);
                    return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_Get", Enum_LogType.Error, ex.Message);
                    return default(T);
                }
            }
        }
        /// <summary>
        /// 获取整个hash的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<T> Hash_GetAll<T>(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var list = redis.GetHashValues(key);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(value);
                        }
                        return result;
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_GetAll", Enum_LogType.Error, ex.Message);
                    return null;
                }

            }
        }
        /// <summary>
        /// 设置缓存过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="datetime"></param>
        public static void Hash_SetExpire(string key, DateTime datetime)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    redis.ExpireEntryAt(key, datetime);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.Hash_SetExpire", Enum_LogType.Error, ex.Message);
                }

            }
        }
        #endregion

        #region -- SortedSet --
        /// <summary>
        ///  添加数据到 SortedSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <param name="score"></param>
        public static bool SortedSet_Add<T>(string key, T t, double score)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.AddItemToSortedSet(key, value, score);
                }
                catch (Exception ex)
                {
                    //MallUtils.WriteLogFile("RedisHelper.SortedSet_Add", Enum_LogType.Error, ex.Message);
                    return false;
                }

            }
        }
        /// <summary>
        /// 移除数据从SortedSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool SortedSet_Remove<T>(string key, T t)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.RemoveItemFromSortedSet(key, value);
                }
                catch (Exception ex)
                {
                   // //MallUtils.WriteLogFile("RedisHelper.SortedSet_Remove", Enum_LogType.Error, ex.Message);
                    return false;
                }
            }
        }
        /// <summary>
        /// 修剪SortedSet
        /// </summary>
        /// <param name="key"></param>
        /// <param name="size">保留的条数</param>
        /// <returns></returns>
        public static long SortedSet_Trim(string key, int size)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.RemoveRangeFromSortedSet(key, size, 9999999);
                }
                catch (Exception ex)
                {
                    ////MallUtils.WriteLogFile("RedisHelper.SortedSet_Trim", Enum_LogType.Error, ex.Message);
                    return 0;
                }

            }
        }
        /// <summary>
        /// 获取SortedSet的长度
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static long SortedSet_Count(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    return redis.GetSortedSetCount(key);

                }
                catch (Exception ex)
                {
                    ////MallUtils.WriteLogFile("RedisHelper.SortedSet_Count", Enum_LogType.Error, ex.Message);
                    return 0;
                }

            }
        }

        /// <summary>
        /// 获取SortedSet的分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<T> SortedSet_GetList<T>(string key, int pageIndex, int pageSize)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(data);
                        }
                        return result;
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    ////MallUtils.WriteLogFile("RedisHelper.SortedSet_GetList", Enum_LogType.Error, ex.Message);
                    return null;
                }
            }
        }


        /// <summary>
        /// 获取SortedSet的全部数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<T> SortedSet_GetListALL<T>(string key)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    var list = redis.GetRangeFromSortedSet(key, 0, 9999999);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(data);
                        }
                        return result;
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    ////MallUtils.WriteLogFile("RedisHelper.SortedSet_GetListALL", Enum_LogType.Error, ex.Message);
                    return null;
                }

            }

        }

        /// <summary>
        /// 设置缓存过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="datetime"></param>
        public static void SortedSet_SetExpire(string key, DateTime datetime)
        {
            using (IRedisClient redis = prcm.GetClient())
            {
                try
                {
                    redis.ExpireEntryAt(key, datetime);
                }
                catch (Exception ex)
                {
                    ////MallUtils.WriteLogFile("RedisHelper.SortedSet_SetExpire", Enum_LogType.Error, ex.Message);
                }

            }
        }

        //public static double SortedSet_GetItemScore<T>(string key,T t)
        //{
        //    using (IRedisClient redis = prcm.GetClient())
        //    {
        //        var data = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
        //        return redis.GetItemScoreInSortedSet(key, data);
        //    }
        //    return 0;
        //}

        #endregion

        public static bool Item_Set<T>(string key, T obj, DateTime? expire = null)
        {
            bool rs = Item_Set<T>(key, obj);
            if (rs && expire != null)
                Item_SetExpire(key, (DateTime)expire);
            return rs;
        }
    }
}
